package com.example.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Component
public class AliyunOssUtils {
    @Value("${aliyun.oss.endpoint}")
     String endpoint;
    @Value("${aliyun.oss.bucketName}")
     String bucketName;
    @Value("${aliyun.oss.accessKeyId}")
     String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
     String accessKeySecret;
    // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
    public  String upload(MultipartFile file) throws  IOException {
        log.info("accessKeyId 和 accessKeySecret:{},{}",accessKeyId,accessKeySecret);
        InputStream is = file.getInputStream();
        log.info("文件流url名称:{}", file.getOriginalFilename());
        String type = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        String objectName = UUID.randomUUID() + type;
// 使用代码嵌入的RAM用户的访问密钥配置访问凭证。
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, is);
        // 创建PutObject请求。
        PutObjectResult result = ossClient.putObject(putObjectRequest);
        log.info("endpoint.split(//)[0]:{}", endpoint.split("//")[0]);
        log.info("endpoint.split(//)[1]:{}", endpoint.split("//")[1]);
        return endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
    }
}
